package com.itjeffrey.autocode.quartz.schedule;

import com.itjeffrey.autocode.entity.ScheduleJobTbEntity;
import com.itjeffrey.autocode.mapper.ScheduleJobTbMapper;
import com.itjeffrey.autocode.quartz.bean.JobBean;
import com.itjeffrey.autocode.util.BeanOprUtils;
import org.quartz.CronTrigger;
import org.quartz.Scheduler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.util.List;

/**
 * 任务调度初始化
 *
 * @From: Jeffrey
 * @Date: 2021/4/16
 */
@Component
public class SchedulerInitialization {

    private static Logger log = LoggerFactory.getLogger(SchedulerInitialization.class);

    private static int createJob_count = 0; //创建Job次数

    private static int updateJob_count = 0; //更新Job次数

    public SchedulerInitialization(){
        log.info("SchedulerInitialization has bean instantiation");
    }

    @Resource
    private Scheduler scheduler ;

    @Resource
    private ScheduleJobTbMapper scheduleJobMapper;

    /**
     * When the System is starting, SchedulerInitialization`s init method is able to be loading,
     * then init all schedulerJob for this system and create many jobs which is will be executing.
     *
     */
    @PostConstruct
    public void init (){
        List<ScheduleJobTbEntity> scheduleJobTbEntities = scheduleJobMapper.selectList(null);
        List<JobBean> jobBeans = BeanOprUtils.copyListProperties(scheduleJobTbEntities, JobBean::new);
        for (JobBean jobBean : jobBeans) {
            CronTrigger cronTrigger = ScheduleContext.getCronTrigger(scheduler,jobBean.getJobId());
            if (cronTrigger == null){
                ScheduleContext.createJob(scheduler,jobBean);
                createJob_count++;
            } else {
                ScheduleContext.updateJob(scheduler,jobBean);
                updateJob_count++;
            }
        }
        log.info("SchedulerInitialization init scheduleJob, createJob_count: {}, updateJob_count: {}",
                createJob_count, updateJob_count);
    }

}
